import {
  getinviteKey,
  getToken
} from '../../utils/storage'

import {
  getInviteList,
  getTokenById,
  getUserInfo,
  getPosterQRcode
} from '../../api/user';
// import { threadId } from 'worker_threads';
import {
  SHOW_COUNT, getSharePng
} from '../../config'
// pages/invite/invite.js

const showCount = 30 || SHOW_COUNT;
let currentPage = 1;
let totalPage = 1;
let user_name = '';

let loading = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    back: false,
    my_invite_key: getinviteKey(),
    my_invite_list: [],

    tip_status: false,
    // 四项收益
    kbx_share_rate: 0.1,
    shar_rate: 0.12,
    earning_giftshare: 0,
    earning_gbox: 0,// 开宝箱收益
    scene: null,
    totalResult: 0,
    bgImage: 'https://ustatic.hudongmiao.com/joymew-assistant/invite/invite_bill.png',
    imagePath: '',
    QRcodeUrl: '',
    incomePercentage: ''
  },
  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    currentPage = 1;
    totalPage = 1;
    // this.requestPosterQRcode()

    if (options.scene) {
      this.setData({
        scene: options.scene
      })
    }
    if (this.data.scene) {
      this.initInviteListBySCENE()
    } else {
      this.initInviteList()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    this.setData({
      back: getCurrentPages().length>1
    })
    // this.createPosterImg()
    loading = false;
    if (getApp().globalData.isNotPageShow) {
      getApp().globalData.isNotPageShow = false;
      return
    }
    user_name = getApp().globalData.user_name || '著名主持人'
    this.setData({
      my_invite_key: getinviteKey(),
      incomePercentage: getApp().globalData.income_rate + '%'
      // my_invite_list: [],
    })
    if(getToken()){
      this.requestPosterQRcode()
    }
 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 

    // return;

    if (currentPage > totalPage) {

      wx.showToast({
        title: '已经到底了', icon: 'none'
      })
      return;
    }

    this.initInviteList();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    getApp().globalData.isNotPageShow = true;
    return {
      title: `${user_name || ''}邀请您加入嗨喵悦动`,
      path: '/pages/regist/regist?share_invite_key=' + this.data.my_invite_key,
      // imageUrl: 'https://ustatic.hudongmiao.com/joymew-assistant/invite/invite_wx.png'
      imageUrl: getSharePng()
    }
  },

  /**
   * 获取邀请人列表 
   */
  initInviteList() {
    
    if (loading) {
      return;
    }

    loading = true;
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    getInviteList({

        showCount: showCount,
        currentPage: currentPage
      })
      .then(res => {
        if (res) {
          this.handleInviteList(res)
        }
        loading = false;
        wx.hideLoading()        
      })
      .catch(err => {
        loading = false;
        wx.hideLoading()        
         
      })
      // .finally(() => {
      //   loading = false;
      //   wx.hideLoading()
      // })

  },

  /**
   * 获取用户信息
   */
  initUserInfo() {

  },
  // 下载网络图片
  downLoadImg: function (netUrl, storageKeyUrl) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: netUrl, //请求的网络图片路径
        success: function (res) {
          //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
          wx.setStorageSync(storageKeyUrl, res.path);
          resolve(res.path);
        },
        fail: function (err) {
          reject(err);
        }
      })
    });
  },
  // 将canvas转换为图片保存到本地
  createPosterImg: function () {
    ;
    let that = this;
    wx.showLoading({
      title: '生成海报中...',
      icon: 'none'
    })
    this.downLoadImg(that.data.bgImage, 'bgPosterUrl').then(() => {
      return this.downLoadImg(that.data.QRcodeUrl, 'QRcodeUrl')
    }).then(() => {
      let context = wx.createCanvasContext('PosterCanvas');
      let bgPath = wx.getStorageSync('bgPosterUrl'); // 图片地址
      // let bgPath = that.data.bgImage
      let QR = wx.getStorageSync('QRcodeUrl')
      // let QR = that.data.QRcodeUrl
      
      // 绘制图片
      context.drawImage(bgPath, 0, 0, 375, 667);
      context.beginPath();
      context.arc(189, 440, 60, 0, 2 * Math.PI) //画出圆
      context.strokeStyle = "#ffffff";
      context.stroke();
      context.clip(); //裁剪上面的圆形

      context.drawImage(QR, 129, 381, 118, 118);
      context.draw()
      context.save()
      // 将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'PosterCanvas',
          success: function (res) {
            const {tempFilePath} = res;
            that.setData({
              imagePath: tempFilePath
            });
            ;
            ;
            that.savePoster()
          },
          fail: function (res) {
             
          }
        });
      }, 1000);

    }).catch((err) => {
       
    });
  },
  // 请求海报中的二维码图片
  requestPosterQRcode: function () {
    let that = this;
    getPosterQRcode({
        page: 'pages/regist/regist',
        scene: this.data.my_invite_key,
        logoPath: getApp().globalData.headerImgPath
      })
      .then(res => {
        this.setData({
          QRcodeUrl: res.smallProgramCode
        })
      })
  },
  // 保存海报到相册
  savePoster: function () {
    
    const that = this
    
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            ;
             
            wx.hideLoading();
          },
          fail: function (res) {}
        })
      },
      fail(err) {
        ;
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  
                },
                fail(failData) {
                  
                },
                complete(finishData) {
                  
                }
              })
            }
          })
        }
      }
    })
  },
  /**
   * 通过scene 获取 用户信息 自动登录 并获取邀请人信息列表
   */
  initInviteListBySCENE() {
    getTokenById({
        scene: this.data.scene
      })
      .then((res) => {
        //  
        if (res.token) {
          wx.setStorageSync('token', res.token);
          getApp().globalData.token = res.token;
          return getUserInfo({
            token: res.token,
          });
        } else {
          return;
        }
      })
      .then((res) => {
        
        if (res) {
          // this.my_invite_key = res.invite_key
          user_name = res.user_name
          wx.setStorageSync('invite_key', res.invite_key);
          wx.setStorageSync('openId', res.wx_openid);
          getApp().globalData.headerImgPath = res.headimg_url
          this.setData({
            my_invite_key: res.invite_key
          })
          return getInviteList({
            showCount: showCount,
            currentPage: currentPage,

          });
        }
      })
      .then((res) => {
        if (res) {
          this.requestPosterQRcode()
          this.handleInviteList(res)
        }
      })
      .catch((err) => {
         

      })
  },
  showTips() {
    const tip_status = this.data.tip_status;
    // 
    this.setData({
      tip_status: !tip_status
    })
  },

  handleInviteList(res) {
    if (res.data) {
      if (res.data.kbx_share_rate || res.data.kbx_share_rate === 0) {
        this.setData({
          kbx_share_rate: res.data.kbx_share_rate
        })
      }

      if (res.data.shar_rate || res.data.shar_rate === 0) {
        this.setData({
          shar_rate: res.data.shar_rate
        })
      }

      if (res.data.totalincome) {
        if (res.data.totalincome.kbx_share_income) {
          res.data.totalincome.earning_gbox = res.data.totalincome.kbx_share_income
        }
        if (res.data.totalincome.gift_share_income) {
          res.data.totalincome.earning_giftshare = res.data.totalincome.gift_share_income
        }


        if (res.data.totalincome.earning_giftshare || res.data.totalincome.earning_giftshare === 0) {
          this.setData({
            earning_giftshare: res.data.totalincome.earning_giftshare
          })
        }

        if(res.data.totalincome.earning_gbox || res.data.totalincome.earning_gbox === 0){
          this.setData({
            earning_gbox: res.data.totalincome.earning_gbox
          })
        }

      }

      if (res.data.varList) {
        let list = res.data.varList;

        currentPage++
        totalPage = res.data.totalPage || 1
        this.setData({
          my_invite_list: this.data.my_invite_list.concat(list),
        })


      }

      if (res.data.jiHuoInfo&&res.data.jiHuoInfo.totalSize) {
        this.setData({
          totalResult: res.data.jiHuoInfo.totalSize
        })
      }

    }
  },

  toCash() {
    wx.navigateTo({
      url: '/pages/invite/cash/cash'
    })

  }
})